<template>
  <div class="home">
    <van-nav-bar
      :title="'ESP32设备（' + deviceData.Online + '）'"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <van-tabs v-model="active" animated swipeable>
      <van-tab title="显示">
        
        <div class="home-content">

          <p class="home-content-area-text" @click="createEZUI">摄像头</p>
          <div id="EZUI" ></div>
          <!-- <video-player
              class="vjs-custom-skin"
              :options="playerOptions"
              :playsinline="true"
              @ready="playerReadied($event)"
            /> -->
          <div class="home-content-cam">
            
            <!-- <video class="full-height full-width" ref="video" controls></video> -->
            <!-- <img class="home-content-cam-img" alt="" /> -->
          </div>
          <p class="home-content-area-text">基本信息</p>
          <transition-group tag="ul" class="home-content-info">
            <li
              class="home-content-info-item"
              @click="onDevices(item, index)"
              v-for="(item, index) in infoData"
              :key="item"
            >
              <img
                :src="item.Icon"
                alt=""
                style="width: 2rem; margin-right: 5px"
              />

              <p class="home-content-info-item-title-name">{{ item.name }}</p>
              <p
                class="home-content-info-item-data"
                :style="{ color: item.color }"
              >
                {{ deviceData[item.dataName] }}Lux
              </p>
            </li>
          </transition-group>
          <p class="home-content-area-text">设备控制</p>
          <div class="home-content-echarts">
            <van-cell
              center
              size="large"
              :label="switchLable('R1')"
              title="开关1"
            >
              <template #right-icon>
                <van-switch
                  v-model="deviceData.R1"
                  :disabled="deviceData.Online !== '在线'"
                  :loading="deviceData.R1Load"
                  @change="onRelayChange(deviceData.R1, 'R1')"
                  size="24"
                />
              </template>
            </van-cell>
            <van-cell
              center
              size="large"
              :label="switchLable('R2')"
              title="开关2"
            >
              <template #right-icon>
                <van-switch
                  v-model="deviceData.R2"
                  :disabled="deviceData.Online !== '在线'"
                  :loading="deviceData.R2Load"
                  @change="onRelayChange(deviceData.R2, 'R2')"
                  size="24"
                />
              </template>
            </van-cell>
            <van-cell
              center
              size="large"
              :label="switchLable('R3')"
              title="开关3"
            >
              <template #right-icon>
                <van-switch
                  v-model="deviceData.R3"
                  :disabled="deviceData.Online !== '在线'"
                  :loading="deviceData.R3Load"
                  @change="onRelayChange(deviceData.R3, 'R3')"
                  size="24"
                />
              </template>
            </van-cell>
            <van-cell
              center
              size="large"
              :label="switchLable('R4')"
              title="开关4"
            >
              <template #right-icon>
                <van-switch
                  v-model="deviceData.R4"
                  :disabled="deviceData.Online !== '在线'"
                  :loading="deviceData.R4Load"
                  @change="onRelayChange(deviceData.R4, 'R4')"
                  size="24"
                />
              </template>
            </van-cell>
          </div>
        </div>
      </van-tab>
      <van-tab title="设置" style="height: calc(100vh - 90px)">
        
        <div class="home-content">
          <van-cell
            class="home-content-cell"
            center
            size="large"
            title="摄像头开关"
          >
            <template #right-icon>
              <van-switch size="24px" @change="onChange()" />
            </template>
          </van-cell>
          <van-field
            class="home-content-cell"
            type="text"
            size="large"
            input-align="right"
            label-width="100px"
            label="摄像头IP地址"
          />
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import EZUIKit from "ezuikit-js";
import { Toast } from "vant";
import * as echarts from "echarts";
import videojs from "video.js";
let Hls = require("hls.js");
var send = {};
export default {
  components: {},
  created() {},
  mounted: function () {
    console.log("mounted 组件挂载完毕状态===============》");
    // setTimeout (this.createEZUI(),2000);
    // this.createEZUI();
    
    // this.myEcharts();
    this.paramsRes = this.$route.params;
    this.deviceData = this.paramsRes.deviceData;
    console.log(this.deviceData.RS485_1);
    // this.getStream(this.hlsURL2);
  },
  data: function () {
    return {
      hlsURL2:
        "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_ts/master.m3u8",
      hlsURL:
        "http://open.ys7.com/v3/openlive/F52057061_1_1.m3u8?expire=1666342315&id=373151771859030016&t=9c7ee9786fd1a5dc0cb0e2ac1274277b61aba9f0981f14b9a33c2aba858e8939&ev=100",
      tempdata: [],
      tempdate: [],
      playerOptions: {
        height: "360",
        autoplay: true,
        playbackRates: [0.7, 1, 1.3, 1.5, 1.7],
        sources: [
          {
            type: "application/x-mpegURL",
            src: "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_ts/master.m3u8", // 你的m3u8地址（必填）
          },
        ],
        poster: "",
      },
      hls: "",
      deviceData: {
        ID: this.id,
        Online: "离线",
        R1: false,
        R2: false,
        R3: false,
        R4: false,
        RS485_1: "--",
        RS485_2: "--",
        RS485_3: "--",
        R1Load: false,
        R2Load: false,
        R3Load: false,
        R4Load: false,
        UpdateDelay: 5000,
      },
      tableData: [],
      // RS485:1,
      infoData: [
        {
          Icon: require("@svg/485.svg"),
          name: "485仪表值1",
          dataName:'RS485_1'
          // data: this.deviceData.RS485,
        },
         {
          Icon: require("@svg/485.svg"),
          name: "485仪表值2",
          dataName:'RS485_2'
          // data: this.deviceData.RS485,
        },
         {
          Icon: require("@svg/485.svg"),
          name: "485仪表值3",
          dataName:'RS485_3'
          // data: this.deviceData.RS485,
        },
      ],
    };
  },

  activated: function () {
    // 在 keepAlive 被激活的时候，调用指定加载页面组件的方法
    // this.LoginCheck();
    // console.log(this.$store.state.username)
  },
  methods: {
    createEZUI(){
      var player =  new EZUIKit.EZUIKitPlayer({
      autoplay: true,
      id: "EZUI",
      accessToken:"at.416g2pvj84vrsd9y3ld4p59j1bb6tdqd-77ccwyw7gl-0g1r829-mmwubqdcl",
      url: "ezopen://open.ys7.com/F52057061/1.live",
      template: "simple", // simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版；
      // 视频上方头部控件
      //header: ["capturePicture", "save", "zoom"], // 如果templete参数不为simple,该字段将被覆盖
      //plugin: ['talk'],                       // 加载插件，talk-对讲
      // 视频下方底部控件
      // footer: ["talk", "broadcast", "hd", "fullScreen"], // 如果template参数不为simple,该字段将被覆盖
      // audio: 1, // 是否默认开启声音 0 - 关闭 1 - 开启
      // openSoundCallBack: data => console.log("开启声音回调", data),
      // closeSoundCallBack: data => console.log("关闭声音回调", data),
      // startSaveCallBack: data => console.log("开始录像回调", data),
      // stopSaveCallBack: data => console.log("录像回调", data),
      // capturePictureCallBack: data => console.log("截图成功回调", data),
      // fullScreenCallBack: data => console.log("全屏回调", data),
      // getOSDTimeCallBack: data => console.log("获取OSDTime回调", data),
      width: 370,
      height: 300
    });
    console.log("player",player);
    },
    switchLable: function (no) {
      var res;
      if (this.deviceData[no + "Load"] === true) {
        res = "正在" + (this.deviceData[no] === true ? "打开" : "关闭");
      } else {
        res = this.deviceData[no] === true ? "打开" : "关闭";
      }
      if (this.deviceData.Online !== "在线") {
        res = "不可用";
      }
      return res;
    },
    formatDate(params) {
      let date = params;
      let formatStr = "HH:mm:ss";
      // 传入日期字符串 - 转成时间戳 - 转成标准时间
      let timeStamp = params.getTime();
      console.log(timeStamp);
      date = new Date(timeStamp);
      formatStr = formatStr.replace(
        new RegExp("yyyy"),
        `${date.getFullYear()}`
      );
      const month = date.getMonth() + 1;
      formatStr = formatStr.replace(
        new RegExp("MM"),
        `${month > 9 ? month : "0" + month}`
      );
      const day = date.getDate();
      formatStr = formatStr.replace(
        new RegExp("dd"),
        `${day > 9 ? day : "0" + day}`
      );
      const hour = date.getHours();
      formatStr = formatStr.replace(
        new RegExp("HH"),
        `${hour > 9 ? hour : "0" + hour}`
      );
      const min = date.getMinutes();
      formatStr = formatStr.replace(
        new RegExp("mm"),
        `${min > 9 ? min : "0" + min}`
      );
      const sec = date.getSeconds();
      formatStr = formatStr.replace(
        new RegExp("ss"),
        `${sec > 9 ? sec : "0" + sec}`
      );
      return formatStr;
    },
    myEcharts() {
      // 基于准备好的dom，初始化echarts实例
      this.speedChart = echarts.init(document.getElementById("echartspeed"));
      this.speedChart.setOption({
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        title: {
          left: "center",
          text: "温度变化记录",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.beatdate,
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          min: -20,
          max: 50,
        },
        series: [
          {
            name: "温度",
            type: "line",
            symbol: "none",
            sampling: "lttb",
            itemStyle: {
              color: "rgb(255, 70, 131)",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgb(255, 158, 68)",
                },
                {
                  offset: 1,
                  color: "rgb(255, 70, 131)",
                },
              ]),
            },
            data: this.tempdata,
          },
        ],
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onRelayChange(res, no) {
      console.log(res);
      var lno = no + "Load";
      // console.log(this.deviceData[lno])
      this.deviceData[lno] = true;
      // this.deviceData.ledload = true;
      send = {};
      send[no] = res;
      this.$mqtt.publish(this.$route.params.sub, send);
    },
    playerReadied(player) {
      console.log("加载成功");
      const track = new videojs.AudioTrack({
        id: "my-spanish-audio-track",
        kind: "translation",
        label: "Spanish",
        language: "es",
      });
      player.audioTracks().addTrack(track);
      // Get the current player's AudioTrackList object.
      const audioTrackList = player.audioTracks();

      // Listen to the "change" event.
      audioTrackList.addEventListener("change", function () {
        // Log the currently enabled AudioTrack label.
        for (let i = 0; i < audioTrackList.length; i++) {
          const track = audioTrackList[i];
          if (track.enabled) {
            videojs.log(track.label);
            return;
          }
        }
      });
    },
    getStream(source) {
      console.log(source);
      if (Hls.isSupported()) {
        console.log("加载成功");
        this.hls = new Hls();
        this.hls.loadSource(source);
        this.hls.attachMedia(this.$refs.video);
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          console.log("加载成功");
          this.$refs.video.play();
        });
        this.hls.on(Hls.Events.ERROR, (event, data) => {
          // console.log(event, data);
          // 监听出错事件
          console.log("加载失败");
        });
      }
    },
    videoPause() {
      if (this.hls) {
        this.$refs.video.pause();
        this.hls.destroy();
        this.hls = null;
      }
    },
    beforeDestroy() {
      this.videoPause();
    },
  },
};
</script>

<style lang="scss" scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
  transform: translateX(100px);
}

.v-enter-active,
.v-leave-to {
  transition: all 0.6s ease;
}

/* v-move 和 v-leave-to 配合使用，能够实现列表后续的元素，逐渐飘上来的效果 */
.v-move {
  transition: all 0.6s ease;
}

.v-leave-to {
  position: absolute;
}
.home {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-flow: column;
  position: absolute;
  &-content {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: left;
    transition: 0.3s;
    overflow-x: hidden;
    &-cam {
      -webkit-animation: xhe 0.5s ease;
      //position: relative;
      margin: 20px 20px 20px 20px;
      // padding: 10px 10px;
      border-radius: 20px 20px 20px 20px;
      box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
      background-color: rgba(255, 255, 255, 0.85);
      backdrop-filter: blur(20px) saturate(180%);
      background-attachment: fixed;
      display: flex;
      justify-content: center;
      align-items: center;
      width: auto;
      &-img {
        border-radius: 20px 20px 20px 20px;
        width: 100%;
        height: auto;
        min-height: 70vw;
      }
    }
    &-myecharts {
      transition: 0.5s;
      text-align: center;
      margin: 0 16px 15px;
      //padding: 0 16px 15px;
      border-radius: 20px 20px 20px 20px;
      // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
      width: auto;
      height: 40vh;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: left;
      background-color: rgba(255, 255, 255, 0.9);
      background-attachment: fixed;
    }
    &-echarts {
      margin: 0 16px 15px;
      width: auto;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: left;
      background-attachment: fixed;
    }
    &-control {
      border-radius: 20px;
      margin-top: 0px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
    &-area {
      &-text {
        margin-left: 20px;
        font-size: 5vw;
        color: white;
        font-weight: 900;
      }
    }
    &-text {
      margin: px2rem(20);
      font-size: px2rem(30);
      color: white;
      font-weight: 600;
      margin-bottom: px2rem(30);
    }
    &-shebei {
      margin-left: px2rem(20);
      margin-bottom: px2rem(5);
      font-size: px2rem(14);
      color: white;
      font-weight: 400;
    }
    &-info {
      transition: 0.5s;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 20px 0 20px;
      &-item {
        transition: 0.5s;
        margin: 5px 0 5px 0;
        text-align: center;
        padding: 12px 16px;
        border-radius: 20px 20px 20px 20px;
        // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
        width: calc(100% - 20px);
        // height: calc(50% - 10px);
        display: flex;
        position: relative;
        flex-direction: row;
        justify-content: left;
        background-color: rgba(255, 255, 255, 0.9);
        background-attachment: fixed;

        &-name {
          margin: auto;
          transition: 0.5s;
          text-align: left;
          color: black;
          //margin-top: 0;
          font-size: 4vw;
        }

        &-data {
          transition: 0.5s;
          // text-align: right;
          color: black;
          margin: auto;
          font-size: 9vw;
          font-weight: 500;
        }
      }
    }
  }
}
.custom-button {
  width: auto;
  padding: 5px 10px;
  color: #fff;
  font-size: 4vw;
  line-height: 5vw;
  text-align: center;
  background-color: #0aadee;
  border-radius: 20px;
}
.van-cell {
  transition: 0.5s;
  padding: 12px 16px;
  border-radius: 20px 20px 20px 20px;
  // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
  // height: calc(50% - 10px);
  background-color: rgba(255, 255, 255, 0.9);
  background-attachment: fixed;
  margin-bottom: 5px;
  margin-top: 5px;
}
</style>
